package airthmetic.exercise.dp;

public class _714_买卖股票的最佳时机含手续费 {

    public static int maxProfit(int[] prices, int fee) {
        int n = prices.length;
        int[][] dp = new int[n][2];

        for(int i=0; i<n; i++){
            if(i==0){
                dp[i][0] = 0;
                dp[i][1] = -prices[i] - fee;
                continue;
            }
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i] );
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i] - fee);
        }

        return dp[n-1][0];
    }

    public static int maxProfit2(int[] prices, int fee) {
        int n = prices.length;
        int i_0 = 0;
        int i_1 = Integer.MIN_VALUE;;
        for(int i=0; i<n; i++){
            int temp = i_0;
            i_0 = Math.max(i_0, i_1 + prices[i]);
            i_1 = Math.max(i_1, temp - prices[i] - fee);
        }

        return i_0;
    }

    public static int maxProfit3(int[] prices, int fee) {
        int n = prices.length;
        int[][] dp = new int[n][2];
        for(int i=0; i<n;i++){
            if(i == 0){
                dp[i][0] = 0;
                dp[i][1] = -prices[i] - fee;
                continue;
            }
            dp[i][0] =Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
            dp[i][1] =Math.max(dp[i-1][1], dp[i-1][0] - prices[i] - fee);
        }

        return dp[n-1][0];
    }

    // 状态压缩练习
    public static int maxProfit4(int[] prices, int fee) {
        int n = prices.length;
        int[] dp = new int[2];
        for(int i=0; i<n;i++){
            if(i == 0){
                dp[0] = 0;
                dp[1] = -prices[i] - fee;
                continue;
            }
            int temp = dp[0];
            dp[0] =Math.max(dp[0], dp[1] + prices[i]);
            dp[1] =Math.max(dp[1], temp - prices[i] - fee);
        }

        return dp[0];


    }

    // 状态压缩练习
    public static int maxProfit5(int[] prices, int fee) {
        int n = prices.length;
        int i_0 = 0;
        int i_1 = Integer.MIN_VALUE;
        for(int i=0; i<n;i++){

            int temp = i_0;
            i_0 =Math.max(i_0, i_1 + prices[i]);
            i_1 =Math.max(i_1, temp - prices[i] - fee);
        }

        return i_0;
    }



    public static void main(String[] args) {
        int[] prices  = new int[]{7,1,5,3,6,4};
        System.out.println(maxProfit(prices,2));
        System.out.println(maxProfit3(prices,2));
    }
}
